package com.controller;

import com.model.Cart;
import com.model.Item;
import com.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value = "/order",method = RequestMethod.POST)
public class OrderRestController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private CartService cartService;

    @Autowired
    private ItemGroupService itemGroupService;

    @Autowired
    private User_OrderService user_orderService;

    @Autowired
    private ItemService itemService;

    /**
     * @return 返回订单号
     */
    @RequestMapping(value = "/",method = RequestMethod.POST)
    public Long createOrder(HttpServletRequest httpServletRequest){
        Long userid= (Long) httpServletRequest.getSession().getAttribute("userid");
        //购物车内商品List
        List<Cart> cartById = cartService.getCartByUserId(userid);

        //形成grouplist
        Long nextGroupIndex = itemGroupService.getNextIndex();
        int price=0;
        //遍历cart
        for(Cart cart:cartById){
            //插入ItemGroup
            itemGroupService.insertItemGroup(nextGroupIndex,cart.getItemid(),cart.getQuantity());
            //cart中item
            Item itemById = itemService.getItemById(cart.getItemid());
            price+=cart.getQuantity()*itemById.getPrice();
        }

        //建立订单
        boolean status = orderService.insertOrder(userid, nextGroupIndex, price, false);

        Long orderid=orderService.getCurrentIndex();

        user_orderService.insertUser_Order(userid,orderid);

        return orderid;
    }

}
